/*
 * =====================================================================================
 *
 *       Filename:  Message.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Fang Dongheng (fndisme), fndisme@163.com
 *   Organization:
 *
 * =====================================================================================
 */
#include "base/Message.h"
#include <cassert>
#include <algorithm>
#include <iostream>
namespace FakeWeiXin {

void Message::swap(Message& msg) {
  std::swap(msg.m_header, m_header);
  std::swap(msg.m_body, m_body);
}

bool Message::buildFromBuffer(const Buffer& buf, Message* msg) {
  assert(msg);
  if (buf.size() < headerSize()) return false;
  Message fillmsg;
  auto ok = fillmsg.m_header.ParseFromArray(&(buf[0]), headerSize());
  if (!ok) return false;
  fillmsg.m_body.assign(buf.begin() + headerSize(), buf.end());
  fillmsg.swap(*msg);
  return true;
}

Buffer Message::toBuffer() const {
  Buffer b(headerSize() + m_body.size());
  auto ok = m_header.SerializeToArray(&(b[0]), headerSize());
  assert(ok);
  std::copy(m_body.begin(), m_body.end(), b.begin() + headerSize());
  return b;
}

void Message::debugPrint() const {
  std::cout << "header: " << m_header.DebugString() << "\n";
  std::cout << "body: " << m_body << "\n";
}
}

